package xyz.chaobei.feature.stream;

import java.util.*;
import java.util.function.Consumer;

/**
 * 测试规约
 *
 * @author <a href='mailto:maruichao52@gmail.com'>MRC</a>
 * @since 2021/2/5
 */
public class ReduceTest {

    public static void main(String[] args) {

        Consumer print = System.out::println;

        List<String> list = new ArrayList<>();

        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");

        print.accept("-----------------------------Reduce string");
        print.accept(list.toString());

        // 字符串拼接
        Optional<String> concat = list.stream().reduce((str1, str2) -> str1.concat(str2));
        concat.ifPresent(System.out::println);

        // 提供第一个值作为首次运算的起始位
        String str = list.stream().reduce("*", (a, b) -> a + b);
        print.accept(str);
        print.accept("-----------------------------");


        print.accept("-----------------------------Reduce number");
        List<Integer> numbers = Arrays.asList(1, 2, 33, 4, 2, 0);
        print.accept(numbers.toString());


        Integer sum = numbers.stream().reduce(0, Integer::sum);
        print.accept("sum=" + sum);

        numbers.stream().reduce(Integer::max).ifPresent(res -> print.accept("max=" + res));
    }


}
